﻿using System;
using System.Collections.Generic;
using Internal.UIOC;
using UIOC.Attributes;

namespace UIOC {

    [InstanceType(InstanceType.Singleton)]
    public interface IService : IObject {
    }

    public abstract class Service : Object, IService {
    }

    public interface IServices {

        T Get<T>() where T : IService;
    }

    internal sealed class Services : IServices, IServiceInternal {

        private readonly Dictionary<Type, IService> m_ServiceDictionary = new();

        public T Get<T>() where T : IService {
            var type = typeof(T);
            if (m_ServiceDictionary.TryGetValue(type, out var service)) {
                service = m_ServiceDictionary[type] = UIOC.Application.TypeMap.Instantiate<T>();
            }
            return (T)service;
        }

        void IServiceInternal.Clear() {
            m_ServiceDictionary.Clear();
        }
    }
}

namespace Internal.UIOC {

    internal interface IServiceInternal {

        public void Clear();
    }
}
